<template>
    <div>
        <div class="filter-container">
            <el-form label-position="left" :inline="true">
                <el-form-item label="渠道类型">
                    <select-app-source-type v-model="search.source_type" :multiple="true"></select-app-source-type>
                </el-form-item>
                <el-form-item label="渠道">
                    <select-app-source v-model="search.source" :type="search.source_type" :multiple="true"></select-app-source>
                </el-form-item>
                <el-form-item label="优化师" prop="spreadUser">
                    <select-spread-user v-model="search.spreadUser" :multiple="true"></select-spread-user>
                </el-form-item>
                <el-form-item label="日期" prop="day">
                    <el-date-picker
                        :clearable="false"
                        v-model="search.day"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                        style="width: 210px;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="">
                    <el-button class="filter-item" icon="el-icon-search" type="primary" :loading="loading" @click="initSearch()">搜索</el-button>
                    <el-button class="filter-item" @click="exportExcel" v-if="$ENABLE_EXPORT">导出本页</el-button>
                    <el-button class="filter-item" icon="el-icon-download" type="primary" plain @click="exportExcel2" v-if="$ENABLE_EXPORT">1.导出推广费</el-button>
                    <el-upload
                        ref="upload"
                        action=""
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="readExcel"
                        class="filter-item">
                        <el-button icon="el-icon-upload2" type="success" plain v-if="$ENABLE_EXPORT">2.导入推广费</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>

        <vxe-table
            :loading="loading"
            ref="xTable"
            highlight-hover-row
            style="width: 100%"
            class="text-center"
            show-footer
            keep-source
            :footer-method="footerMethod"
            :tooltip-config="tooltipConfig"
            :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
            :max-height="maxHeight">
            <vxe-table-column title="渠道" field="source" formatter="formatAppSourceName" min-width="150" fixed="left" show-overflow/>
            <vxe-table-column title="日期" field="day" width="100" fixed="left" sortable sort-by="day"/>
            <vxe-table-column title="推广费" field="spreadCost" formatter="formatHumanRmb" min-width="110" fixed="left" sortable sort-by="spreadCost" :title-help="{message: '排序仅针对当前页; 鼠标放到推广费上会显示对应公式(如果有)'}"/>
            <vxe-table-column title="活跃人数" field="loginUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="去新增活跃人数" field="loginOldUser" formatter="formatHuman" width="80" :visible="false"/>
            <vxe-table-column title="激活人数" field="authAllowUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="注册人数" field="registerUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="注册率" field="registerScale" formatter="formatPercent" min-width="80"/>
            <vxe-table-column title="注册成本" field="registerCost" :formatter="['formatHumanRmb', 2]" min-width="80"/>
            <vxe-table-column title="24H人数" field="payFirstOldUser24" formatter="formatHuman" min-width="70"/>
            <vxe-table-column title="24H成本" field="payFirstOldUser24Cost" formatter="formatHumanRmb" min-width="70"/>
            <vxe-table-column title="48H人数" field="payFirstOldUser48" formatter="formatHuman" min-width="70"/>
            <vxe-table-column title="48H成本" field="payFirstOldUser48Cost" formatter="formatHumanRmb" min-width="70"/>
            <vxe-table-column title="首日充值人数" field="payFirstUser" formatter="formatHuman" min-width="100"/>
            <vxe-table-column title="首日充值率" field="payFirstUserScale" formatter="formatPercent" min-width="90" :class-name="columnClass"/>
            <vxe-table-column title="首日充值成本" field="payFirstCost" :formatter="['formatHumanRmb', 1]" min-width="100"/>
            <vxe-table-column title="首日充值金额" field="payFirst" formatter="formatHumanRmb" min-width="100"/>
            <vxe-table-column title="首日积分" field="thirdExchangeFirst" :formatter="['formatW', 1]" min-width="90" :class-name="columnClass"/>
            <vxe-table-column title="首日积分人数" field="thirdExchangeFirstUser" formatter="formatHuman" min-width="100"/>
            <vxe-table-column title="首日积分率" field="thirdExchangeFirstUserScale" formatter="formatPercent" min-width="80" :class-name="columnClass"/>
            <vxe-table-column title="首日积分转化率" field="payFirstUserThirdExchangeFirstUserScale" formatter="formatPercent" min-width="80" :title-help="{message: '首日充值人数/首日积分人数'}"/>
            <vxe-table-column title="去新增充值人数" field="payOldUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="去新增充值金额" field="payOld" formatter="formatHumanRmb" min-width="90"/>
            <vxe-table-column title="充值人数" field="payUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="充值率" field="payUserScale" formatter="formatPercent" min-width="90"/>
            <vxe-table-column title="充值金额" field="pay" formatter="formatHumanRmb" min-width="90"/>
            <vxe-table-column title="总积分" field="thirdExchange" :formatter="['formatW', 1]" min-width="90"/>
            <vxe-table-column title="总积分人数" field="thirdExchangeUser" formatter="formatHuman" min-width="80"/>
            <vxe-table-column title="总积分率" field="thirdExchangeUserScale" formatter="formatPercent" min-width="80"/>
            <vxe-table-column title="积分占比" field="thirdExchangePayScale" :formatter="['formatPercent', 2]" min-width="80"/>
            <vxe-table-column title="ARPPU" field="arppu" :formatter="['formatHumanRmb', 2]" min-width="80"/>
            <vxe-table-column title="新增ARPPU" field="arppuFirst" :formatter="['formatHumanRmb', 2]" width="90"/>
            <vxe-table-column title="去新增ARPPU" field="arppuOld" :formatter="['formatHumanRmb', 2]" width="100"/>
            <vxe-table-column title="ARPU" field="arpu" :formatter="['formatHumanRmb', 2]" min-width="80"/>
            <vxe-table-column title="新增ARPU" field="arpuFirst" :formatter="['formatHumanRmb', 2]" width="80"/>
            <vxe-table-column title="去新增ARPU" field="arpuOld" :formatter="['formatHumanRmb', 2]" width="100"/>
            <vxe-table-column title="首日市场ROI" field="roiMarketFirst" :formatter="['formatPercent', 2]" min-width="100"/>
            <vxe-table-column title="首日实际ROI" field="roiFirst" :formatter="['formatPercent', 2]" min-width="100"/>
            <vxe-table-column title="市场ROI" field="roiMarket" :formatter="['formatPercent', 2]" min-width="80"/>
            <vxe-table-column title="实际ROI" field="roi" :formatter="['formatPercent', 2]" min-width="80"/>
<!--            <vxe-table-column title="运营毛利" field="operationProfit" formatter="formatHumanRmb" min-width="100" :title-help="{message: '充值 - 充值通道费用 - 推广费'}"/>-->
            <vxe-table-column title="渠道细分" field="spreadChannel" :edit-render="{name: 'input', attrs: {type: 'text'}}" min-width="110"/>
            <vxe-table-column title="推广方式" field="spreadType" :edit-render="{name: 'input', attrs: {type: 'text'}}" min-width="110"/>
            <vxe-table-column title="优化师" field="spreadUser" :edit-render="{name: 'input', attrs: {type: 'text'}}" min-width="110"/>
        </vxe-table>

        <div class="mt-10 pull-right">
            <el-button type="primary" @click="simpleUpdate">保存数据</el-button>
        </div>

        <el-pagination
            class="pull-left"
            background
            :current-page.sync="pageNo"
            :page-sizes="pageOptions.pageSizesList"
            :page-size="pageSize"
            :layout="pageOptions.layout"
            :total="totalDataNumber"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
        </el-pagination>

    </div>
</template>

<script>
import SelectAppSourceType from '~/components/Select/app-source-type';
import SelectSpreadUser from '~/components/Select/spread-user';
import XLSX from "xlsx";

export default {
    components: {
        SelectAppSourceType,
        SelectSpreadUser,
    },
    data() {
        return {
            search: {
                source: '',
                spreadUser: '',
                source_type: [],
                day: [],
            },
            loading: false,
            selected: [],
            tableData: [],
            pageNo: 1,
            pageSize: 100,
            totalDataNumber: 0,
            pageOptions: this.$store.state.backend.pageOptions,
            pageCount: 0,
            options: this.$store.state.operation.options.bulletLog,
            spreadUsers: [],

            tooltipConfig: {
                showAll: true,
                enterable: true,
                contentMethod: ({ type, column, row, items, _columnIndex }) => {
                    const { field } = column
                    // 重写默认的提示内容
                    if (field === 'spreadCost') {
                        if (type === 'header' || type === 'footer' || !row.cpaCostFormula) {
                            return '';
                        }
                        return '公式 = '+row.cpaCostFormula;
                    }
                    // 其余的单元格使用默认行为
                    return null
                }
            }
        }
    },
    computed: {
        maxHeight() {
            return this.$store.state.backend.windowInnerHeight - 240;
        },
    },
    methods: {
        handleSizeChange(val) {
            this.pageNo = 1;
            this.pageSize = parseInt(`${val}`);
            this.handleSearch();
        },
        handleCurrentChange(val) {
            this.pageNo = parseInt(`${val}`);
            this.handleSearch();
        },
        handleSelectionChange(val) {
            this.selected = val;
        },
        handleSearch() {
            this.$nextTick(() => {
                let sortColumn = this.$refs.xTable.getSortColumns()[0];
                this.loading = true;
                let filter = Object.assign({}, this.search, {
                    page: this.pageNo,
                    pageSize: this.pageSize,
                });
                this.$store.dispatch('spreadData/Daily', filter).then(({data}) => {
                    this.$refs.xTable.reloadData(data.data);
                    if (sortColumn) this.$refs.xTable.sort(sortColumn.field, sortColumn.order);
                    this.totalDataNumber = data.meta.total;
                }).finally(() => {
                    this.loading = false;
                });
            })
        },
        initData() {
            this.initSearchDate();
            this.handleSearch();
        },
        initSearchDate() {
            this.search.day = [
                moment().format('yyyy-MM-DD'),
                moment().format('yyyy-MM-DD')
            ];
        },
        initSearch() {
            this.pageNo = 1;
            this.handleSearch();
        },
        exportExcel () {
            this.$refs.xTable.exportData({
                filename: '推广数据-' + this.$route.meta.title,
                type: 'xlsx'
            })
        },
        exportExcel2() {
            this.$refs.xTable.exportData({
                filename: '推广费-' + this.search.day,
                type: 'xlsx',
                isFooter: false,
                columnFilterMethod ({column, $columnIndex}) {
                    // 仅保留渠道和推广费
                    return['渠道', '日期', '推广费'].includes(column.title);
                }
            }).then(() => {
                this.$alert('导出的Excel中, 无须修改的渠道请手动删除, 防止误操作！ <br/>日期只支持文本格式, 建议不要手动修改。', {
                    dangerouslyUseHTMLString: true,
                });
            });
        },
        readExcel(file, fileList) {
            // 文件列表只显示一个文件
            const fileReader = new FileReader();
            fileReader.onload = (ev) => {
                try {
                    const data = ev.target.result;
                    const workbook = XLSX.read(data, {
                        type: 'binary'
                    });
                    // 取1个sheet
                    let sheet, json;
                    for (let i = 0; i < 1; i++) {
                        sheet = Object.keys(workbook.Sheets)[i];
                        json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {
                            header: 'A'
                        });
                        this.getSheetData(i, json);
                    }

                } catch (e) {
                    console.log(e)
                }
            };
            fileReader.readAsBinaryString(file.raw);
        },
        // i => sheet index, json => sheet data
        getSheetData(i, json) {
            let data = [];
            json.forEach((v, k) => {
                // 跳过第一行
                if (k < 1) return;
                if (!v.A) return;

                let rowData = {
                    source: v.A.split(' ')[0],
                    day: v.B.toString(),
                    cpaCost: v.C.toString().trim().replace(',', ''),
                };

                data.push(rowData);
            });
            this.$store.dispatch('spreadData/DailyBatchUpdate', {data: data}).then(res => {
                this.$message.success('保存成功');
                this.handleSearch();
            });
        },
        footerMethod({ columns, data }) {
            let loginOldUser = 0;
            data.map(v => loginOldUser += v.loginOldUser);

            return this.$helper.vxeFooter(columns, data, null, (sums, allFields) => {
                // 计算 payUserScale
                sums[allFields.payUserScale] = this.$helper.calcDivision(sums[allFields.payUser], sums[allFields.loginUser])
                // 计算 payFirstUserScale
                sums[allFields.payFirstUserScale] = this.$helper.calcDivision(sums[allFields.payFirstUser], sums[allFields.registerUser])
                // 计算 thirdExchangeUserScale
                sums[allFields.thirdExchangeUserScale] = this.$helper.calcDivision(sums[allFields.thirdExchangeUser], sums[allFields.loginUser])
                // 计算 thirdExchangeFirstUserScale
                sums[allFields.thirdExchangeFirstUserScale] = this.$helper.calcDivision(sums[allFields.thirdExchangeFirstUser], sums[allFields.registerUser])
                // 计算 registerCost
                sums[allFields.registerCost] = this.$helper.calcDivision(sums[allFields.spreadCost], sums[allFields.registerUser])
                // 计算 arpu
                sums[allFields.arpu] = this.$helper.calcDivision(sums[allFields.pay], sums[allFields.loginUser])
                // 计算 arppu
                sums[allFields.arppu] = this.$helper.calcDivision(sums[allFields.pay], sums[allFields.payUser])
                // 计算 新增arpu
                sums[allFields.arpuFirst] = this.$helper.calcDivision(sums[allFields.payFirst], sums[allFields.registerUser])
                // 计算 新增arppu
                sums[allFields.arppuFirst] = this.$helper.calcDivision(sums[allFields.payFirst], sums[allFields.payFirstUser])
                // 计算 去新增arpu
                sums[allFields.arpuOld] = this.$helper.calcDivision(sums[allFields.payOld], loginOldUser)
                // 计算 去新增arppu
                sums[allFields.arppuOld] = this.$helper.calcDivision(sums[allFields.payOld], sums[allFields.payOldUser])
                // 计算 roi
                sums[allFields.roi] = this.$helper.calcDivision((sums[allFields.pay] - sums[allFields.thirdExchange] / this.$CURRENCY_HB_SCALE * 100), sums[allFields.spreadCost])
                // 计算 roiFirst
                sums[allFields.roiFirst] = this.$helper.calcDivision((sums[allFields.payFirst] - sums[allFields.thirdExchangeFirst] / this.$CURRENCY_HB_SCALE * 100), sums[allFields.spreadCost])
                // 计算 市场roi
                sums[allFields.roiMarket] = this.$helper.calcDivision(sums[allFields.pay], sums[allFields.spreadCost])
                // 计算 市场roiFirst
                sums[allFields.roiMarketFirst] = this.$helper.calcDivision(sums[allFields.payFirst], sums[allFields.spreadCost])
                // 计算 payFirstCost
                sums[allFields.payFirstCost] = this.$helper.calcDivision(sums[allFields.spreadCost], sums[allFields.payFirstUser])
                // 计算 payFirstOldUser24Cost
                sums[allFields.payFirstOldUser24Cost] = this.$helper.calcDivision(sums[allFields.spreadCost], sums[allFields.payFirstOldUser24])
                // 计算 payFirstOldUser48Cost
                sums[allFields.payFirstOldUser48Cost] = this.$helper.calcDivision(sums[allFields.spreadCost], sums[allFields.payFirstOldUser48])
                // 计算 thirdExchangePayScale
                sums[allFields.thirdExchangePayScale] = this.$helper.calcDivision(sums[allFields.thirdExchange] / this.$CURRENCY_HB_SCALE * 100, sums[allFields.pay])
                // 计算 registerScale
                sums[allFields.registerScale] = this.$helper.calcDivision(sums[allFields.registerUser], sums[allFields.authAllowUser])
                // 计算 payFirstUserThirdExchangeFirstUserScale
                sums[allFields.payFirstUserThirdExchangeFirstUserScale] = this.$helper.calcDivision(sums[allFields.payFirstUser], sums[allFields.thirdExchangeFirstUser])
                return sums;
            });
        },
        columnClass({row, column}) {
            // 绿色表示安全  红色为需要警戒
            if (column.property === 'payFirstUserScale') {
                if (!row.payFirstUserScale) return '';
                return row.payFirstUserScale >= 0.08 ? 'color-success' : 'color-danger';
            } else if (column.property === 'thirdExchangeFirst') {
                if (!row.thirdExchangeFirst) return '';
                return row.thirdExchangeFirst <= row.payFirst*0.6 ? 'color-success' : 'color-danger';
            } else if (column.property === 'thirdExchangeFirstUserScale') {
                if (!row.thirdExchangeFirstUserScale) return '';
                return (row.thirdExchangeFirstUserScale < 0.6) ? 'color-success' : 'color-danger';
            }
            return '';
        },
        simpleUpdate() {
            const $table = this.$refs.xTable;
            const updateRecords = $table.getUpdateRecords();
            if (!updateRecords.length) {
                this.$message.error('未修改表格');
                return false;
            }

            const data = updateRecords.map(v => {
                return {
                    _id: v._id,
                    spreadChannel: v.spreadChannel || '',
                    spreadType: v.spreadType || '',
                    spreadUser: v.spreadUser || '',
                }
            })
            this.$confirm('是否确认?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                data.map(v => {
                    this.loading = true;
                    this.$store.dispatch('spreadData/DailySimpleUpdate', v).then(res => {

                    }).finally(() => {
                        this.loading = false;
                    });
                });

                // 清除编辑状态
                updateRecords.map(row => {
                    $table.reloadRow(row, {});
                });

                this.$message({
                    message: '保存成功, 页面即将刷新',
                    type: 'success',
                    onClose: () => {
                        // 更新优化师数据
                        this.$store.dispatch('spreadData/GetSpreadUsers');

                        this.handleSearch();
                    }
                });
            }).catch(() => {
                this.handleSearch();
            });
        },
    },
    created() {
        this.initData();
    }
}
</script>

<style lang="scss" scoped>
#app .el-form-item {
    margin-bottom: 0;
}
</style>

